package com.j;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

/**
 * Created by zhuangjianhui_91 on 2015/10/27.
 */
@ServerEndpoint("/websockettest")
public class WebSocketTest {

	private static Map<String, Session> sessionMap = new Hashtable<>();

	@OnMessage
	public void onMessage(String message, Session session) throws IOException, InterruptedException {
		System.out.println("receive msg:" + message);

		JSONObject msgObject = JSON.parseObject(message);

		broadcastAll(msgObject.getIntValue("houseId"), msgObject.getString("msg"));

	}

	@OnOpen
	public void onOpen(Session session) {
		sessionMap.put(session.getId(), session);
		System.out.println("Client connected,sessionId:"+session.getId());
	}

	@OnClose
	public void onClose(Session session, CloseReason closeReason) {
		sessionMap.remove(session.getId());

		System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
	}

	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误");
		error.printStackTrace();
	}

	/**
	 * 
	 * 广播给所有人
	 * 
	 * 
	 * @param message
	 * 
	 */
	public static void broadcastAll(int houseId, String message) {
		Set<Map.Entry<String, Session>> set = sessionMap.entrySet();

		for (Map.Entry<String, Session> i : set) {
			try {
				i.getValue().getBasicRemote().sendText("房间" + houseId +":" + message);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
